package jnpf.scheduletask.task;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jnpf.base.UserInfo;
import jnpf.base.entity.DataInterfaceEntity;
import jnpf.base.service.DataInterfaceService;
import jnpf.base.service.DbLinkService;
import jnpf.scheduletask.entity.TimeTaskEntity;
import jnpf.scheduletask.model.ContentNewModel;
import jnpf.scheduletask.model.TaskParameterModel;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import jnpf.util.data.DataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Api和数据接口使用
 *
 * @author ：JNPF开发平台组
 * @version: V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date ：2022/3/23 9:25
 */
@Component
public class ScheduleTaskHandler {

    @Autowired
    private DataInterfaceService dataInterfaceService;
    @Autowired
    private DbLinkService dbLinkService;

    @XxlJob("defaultHandler")
    public void defaultHandler() {
        // 获取参数
        String param = XxlJobHelper.getJobParam();
        // 转换成模型
        TimeTaskEntity entity = JsonUtil.getJsonToBean(param, TimeTaskEntity.class);
        ContentNewModel model = JsonUtil.getJsonToBean(entity.getExecuteContent(), ContentNewModel.class);
        // 如果是http
        if (entity != null && "1".equals(entity.getExecuteType())) {
            Boolean callHttp = callHttp(model);
//            if (callHttp) {
//                XxlJobHelper.handleResult(ReturnT.SUCCESS_CODE, "调用成功");
//            } else {
//                XxlJobHelper.handleResult(ReturnT.FAIL_CODE, "调用失败");
//            }
        } else if (entity != null && "2".equals(entity.getExecuteType())) {
            boolean callSql = callSql(model);
//            if ( callSql) {
//                XxlJobHelper.handleResult(ReturnT.SUCCESS_CODE, "调用成功");
//            } else {
//                XxlJobHelper.handleResult(ReturnT.FAIL_CODE, "调用失败");
//            }
        }
    }

    // ---------------START callSQL

    /**
     * 调用SQL
     *
     * @param model 系统调度参数
     */
    private boolean callSql(ContentNewModel model) {
        try {
            UserInfo userInfo = model.getUserInfo();
            // 切换数据源
            if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString());
            }
            // 得到数据接口信息
            String tenantId = StringUtil.isNotEmpty(model.getUserInfo().getTenantId()) ? model.getUserInfo().getTenantId() : "0";
            DataInterfaceEntity entity = dataInterfaceService.getInfo(model.getInterfaceId());
            if (entity != null) {
                Map<String, String> map = null;
                if (model.getParameter() != null && model.getParameter().size() > 0) {
                    map = new HashMap<>(16);
                    for (TaskParameterModel parameterModel : model.getParameter()) {
                        if (StringUtil.isNotEmpty(parameterModel.getValue())) {
                            map.put(parameterModel.getField(), parameterModel.getValue());
                        } else {
                            map.put(parameterModel.getField(), parameterModel.getDefaultValue());
                        }
                    }
                }
                dataInterfaceService.infoToId(entity.getId(), tenantId, map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    // ---------------START callHttp

    /**
     * HTTP调用
     *
     * @param model 系统调度参数
     * @return
     */
    private Boolean callHttp(ContentNewModel model) {
        try {
            UserInfo userInfo = model.getUserInfo();
            // 切换数据源
            if (StringUtil.isNotEmpty(userInfo.getTenantId())) {
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString());
            }
            // 得到数据接口信息
            String tenantId = StringUtil.isNotEmpty(model.getUserInfo().getTenantId()) ? model.getUserInfo().getTenantId() : "0";
            DataInterfaceEntity entity = dataInterfaceService.getInfo(model.getInterfaceId());
            if (entity != null) {
                Map<String, String> map = null;
                if (model.getParameter() != null && model.getParameter().size() > 0) {
                    map = new HashMap<>(16);
                    for (TaskParameterModel parameterModel : model.getParameter()) {
                        if (StringUtil.isNotEmpty(parameterModel.getValue())) {
                            map.put(parameterModel.getField(), parameterModel.getValue());
                        } else {
                            map.put(parameterModel.getField(), parameterModel.getDefaultValue());
                        }
                    }
                }
                dataInterfaceService.infoToId(entity.getId(), tenantId, map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
